<?php
require_once( './includes/WebStart.php' );


if( $wgUser->isLoggedIn() &&  is_numeric($_GET[id_file]) && is_numeric($_GET[rating_file])) {
  
  $id_user = $wgUser->getId();
  $id_file = mysql_real_escape_string($_GET[id_file]);
  $rating = mysql_real_escape_string($_GET[rating_file]);


  //FIRST SELECT IF EXISTS
  $dbr = wfGetDB( DB_SLAVE );
  $sql = "SELECT id_rate_file, id_rating_file, id_user, rating
            FROM ss_file_rating WHERE id_rating_file = '$id_file' AND id_user = '$id_user'";
  
  $res = $dbr->query( $sql );
  
  if ( $row = $dbr->fetchObject( $res ) ) {  //if exists update the rating
   
    
    $dbr->freeResult( $res );
      
      $dbw =& wfGetDB( DB_MASTER );
      $dbw->begin();  
       
      
      $sql = "UPDATE  ss_file_rating SET rating = '$rating'
             WHERE id_rating_file = '$id_file' AND id_user = '$id_user'";
      
      
      $dbw->query( $sql );
		  $dbw->commit();
      
		
    
     
  }else { //if not exists the query search, create new rating row
  
  //INSERT NEW
  $dbw =& wfGetDB( DB_MASTER );
  $dbw->begin();   
  $sql = "INSERT INTO ss_file_rating (id_rating_file, id_user, rating)
            VALUES ('$id_file' , '$id_user', '$rating')";
       
  $dbw->query( $sql );
  $dbw->commit();
  
  }
  
} else {
  die(-1);
}
